package com.hust.hui.quick.service.repository;

import com.hust.hui.quick.service.dao.UserMapper;
import com.hust.hui.quick.service.domain.UserEntity;
import com.hust.hui.quick.service.exception.IllegalUserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by yihui on 2017/7/14.
 */
@Repository
public class UserRepository {

    @Autowired
    private UserMapper userMapper;


    public void init() {
        userMapper.create();
    }


    public long regist(UserEntity userEntity) {
        checkName(userEntity.getName());

        int ans = userMapper.insert(userEntity);
        if (ans > 0) {
            return userEntity.getId();
        } else {
            throw new IllegalUserException("regist user into table failed!");
        }
    }


    public UserEntity queryById(long id) {
        Map<String, Object> params = new HashMap<>(1);
        params.put("id", id);
        return queryOne(params);
    }

    public UserEntity queryByName(String name) {
        checkName(name);

        Map<String, Object> params = new HashMap<>(1);
        params.put("name", name);
        return queryOne(params);
    }

    public UserEntity queryByEmail(String email) {
        Map<String, Object> params = new HashMap<>(1);
        params.put("email", email);
        return queryOne(params);
    }


    public UserEntity queryOne(Map<String, Object> map) {
        if (map.containsKey("id") || map.containsKey("name") || map.containsKey("email")) {
            return userMapper.queryOne(map);
        }

        throw new IllegalUserException("userId/username/email should at least be one exists in query condition!");
    }


    public boolean update(UserEntity userEntity) {
        int ans = userMapper.update(userEntity);
        return ans >= 1;
    }



    private void checkName(String name) {
        if (name == null || name.length() > 40) {
            throw new IllegalUserException("user name should not be null or username's length less than 40");
        }
    }

}
